<template>
    <div class="main-head-content" ref="main-head-content">
        <div class="main-head-container" ref="main-head-container">
            <template v-for="item of headMenus">
                <template v-if="item.key != 'RxMenuMore'">
                    <div
                        class="head-menu-item"
                        :class="{ 'head-item-active': appKey === item.key }"
                        :key="item.key"
                        @click="handClick(item)"
                    >
                        <rx-use-icon v-model="item.icon" />
                        <span class="menu-item-title">{{ getName(item.title) }}</span>
                    </div>
                </template>
                <template v-else>
                    <div
                        class="head-menu-more"
                        @click.stop="
                            showMenu = true
                            activeMore = true
                        "
                        :class="{ 'head-item-active': activeItem(appKey) === 'RxMenuMore' }"
                        ref="head-menu-more"
                    >
                        <div class="head-menu-more-item">
                            <my-icon :type="item.icon" />
                            <span class="menu-item-title">{{ $ti18('rxList.moreBtn', '更多') }}</span>
                        </div>
                        <div class="head-menu-down" v-show="showMenu">
                            <div class="head-menu-dialog">
                                <template v-for="menu of item.children">
                                    <div
                                        class="dialog-item"
                                        :class="{ 'dialog-item-active': appKey === menu.key }"
                                        :key="menu.key"
                                        @click="handClick(menu)"
                                    >
                                        <div class="dialog-item-icon">
                                            <rx-use-icon v-model="menu.icon" />
                                        </div>
                                        <span class="dialog-item-title">{{ getName(menu.title) }}</span>
                                    </div>
                                </template>
                            </div>
                        </div>
                    </div>
                </template>
            </template>
        </div>
    </div>
</template>

<script>
import elementResizeDetectorMaker from 'element-resize-detector'
import { RxUseIcon } from '@lowcode/jpaas-common-lib'
import { mapState, mapGetters } from 'vuex'

export default {
    name: 'MainHead',
    components: { RxUseIcon },
    props: {
        /**
         * 菜单
         */
        menus: {
            type: Array,
        },
        /**
         * 背景
         */
        background: {
            type: String,
        },
    },
    data() {
        return {
            breakIndex: null,
            showMenu: false,
        }
    },
    computed: {
        ...mapState({
            // user,admin
            frontType: (state) => state.appSetting.frontType,
            //当前选中的菜单KEY
            activeKey: (state) => state.appSetting.activeKey[state.appSetting.frontType],
            //当前应用key
            appKey: (state) => state.appSetting.appKey[state.appSetting.frontType],
        }),

        /**
         * 当前显示的APP
         * @returns {*[]}
         */
        apps() {
            let apps = this.menus
                .filter((item) => {
                    return item.isApp == 'Y'
                })
                .sort((app1, app2) => {
                    return app1.sn - app2.sn
                })

            return apps
        },

        /**
         * 显示到头部的应用
         * @returns {*[]}
         */
        headMenus() {
            let { apps, breakIndex } = this
            let arr = []
            if (breakIndex == null) {
                arr = [...apps]
            } else {
                arr = [
                    ...apps.slice(0, breakIndex),
                    {
                        title: '更多',
                        key: 'RxMenuMore',
                        icon: 'iconVue3_manage',
                        children: [...apps.slice(breakIndex)],
                    },
                ]
            }
            return arr
        },
        activeItem() {
            return (key) => {
                let hasSelect = this.headMenus
                    .find((item) => item.key === 'RxMenuMore')
                    .children.find((item) => item.key === key)
                if (hasSelect) {
                    return 'RxMenuMore'
                }
                return key
            }
        },
    },
    created() {},
    mounted() {
        //计算展示几个头部栏目
        this.watchSize()
        this.$nextTick(() => {
            let self = this
            document.addEventListener('click', function () {
                self.showMenu = false
            })
        })
    },
    methods: {
        getName(name) {
            /*if(!name.includes('zh-CN')){
                return name ;
            }
            let fn = new Function('return '+ name)()
            let language = window.localStorage.getItem('language') || 'zh-CN';
            return fn[language]*/
            return this.$i18(name)
        },
        i18n(name, text, key) {
            return this.$ti18(name, text, 'layoutsLang', key)
        },
        getBreakIndex(element, width) {
            //获取更多按钮的 宽度；
            let headMenuMore = this.$refs['head-menu-more']
            let headMenuMore_width = headMenuMore && headMenuMore[0] ? headMenuMore.offsetWidth : 90

            let headMenuItem = element.querySelectorAll('.head-menu-item')
            if (!headMenuItem) {
                return
            }
            let _width = headMenuMore_width,
                menuBreakCount = null
            for (let i = 0; i < headMenuItem.length; i++) {
                //如果每一个菜单的宽度之和 大于 外部盒子 ；
                //则取前面的下标；
                if (!headMenuItem[i]) {
                    break
                }
                if (_width > width && headMenuItem[i - 1]) {
                    let w2 = headMenuItem[i - 1].offsetWidth
                    menuBreakCount = _width - w2 + 90 > width ? i - 1 : i
                    break
                }
                let w = headMenuItem[i].offsetWidth
                _width += w
            }
            return menuBreakCount
        },
        getItemWidth(element) {
            let items = element.querySelectorAll('.head-menu-item')
            let width = Array.from(items).reduce((a, b) => {
                let w = b.offsetWidth
                return a + w
            }, 0)
            return width
        },
        watchSize() {
            const erd = elementResizeDetectorMaker()
            erd.listenTo(this.$refs['main-head-content'], (element) => {
                this.breakIndex = null
                this.$nextTick(() => {
                    let width = element.offsetWidth
                    let item_width = this.getItemWidth(element)
                    if (item_width > width) {
                        let idx = this.getBreakIndex(element, width)
                        this.breakIndex = idx
                    }
                })
            })
        },
        handClick(value) {
            console.log(value)
            this.$emit('handClick', value)
        },
    },
    watch: {
        keyword: function (val) {
            this.search()
        },
        frontType() {
            this.watchSize()
        },
    },
}
</script>

<style scoped>
.main-head-content {
    height: 100%;
    position: relative;
    display: flex;
    align-items: center;
    font-size: 16px;
}
.main-head-container {
    display: flex;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    align-items: center;
    height: 100%;
    flex: 1;
    gap: 0 4px;
}
.head-menu-more,
.head-menu-item {
    display: flex;
    align-items: center;
    padding: 0 16px;
    white-space: nowrap;
    cursor: pointer;
    height: 32px;
    border-radius: 4px;
}
.head-menu-more-item,
.head-menu-item {
    color: #fff;
}
.main-head-content .menu-item-title {
    display: inline-block;
    padding-left: 4px;
    font-size: 15px;
    margin-top: -1px;
}

.main-head-content .head-menu-more .menu-item-title {
    vertical-align: 2px;
}

.main-head-content .head-menu-more {
    position: relative;
}
.head-menu-down {
    position: absolute;
    padding: 16px;
    border-radius: 6px;
    background: #fff;
    box-shadow: 0 0 13px 0 rgba(6, 0, 1, 0.17);
    top: 50px;
    right: 0;
    z-index: 9;
    font-size: 14px;
    min-width: 160px;
}
.head-menu-dialog {
    display: grid;
    grid-auto-flow: column;
    grid-template-rows: repeat(auto-fit, 40px);
    grid-gap: 0 20px;
    max-height: 201px;
}

.dialog-item {
    display: flex;
    align-items: center;
    height: 40px;
    border-radius: 4px;
    position: relative;
    padding: 0 6px;
}
.dialog-item-icon {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 24px;
    height: 24px;
    background-color: #1a5eff;
    color: #fff;
    margin-right: 6px;
    border-radius: 4px;
}
.dialog-item-title {
    max-width: 100px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}
.dialog-item:hover,
.dialog-item.dialog-item-active {
    background-color: #f3f7ff;
}
.dialog-item:hover .dialog-item-title {
    color: #1a5eff;
}
.head-menu-item.head-item-active,
.head-menu-more.head-item-active {
    background-color: rgba(255, 255, 255, 0.24);
}
</style>
